package servlet;

import dao.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/checkUsername")
public class UsernameServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");

        BaseDao baseDao = new BaseDao();
        Connection conn = baseDao.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            String sql = "SELECT COUNT(*) AS count FROM users WHERE username = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                int count = rs.getInt("count");
                response.setContentType("text/jsp;charset=UTF-8");
                if (count == 0) {
                    response.getWriter().print("true");
                } else {
                    response.getWriter().print("false");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            baseDao.closeAll(conn, pstmt, rs);
        }
    }
}

